package com.hghivln.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hghivln.constants.Constants;
import com.hghivln.mapper.MenuMapper;
import com.hghivln.pojo.domain.Menu;
import com.hghivln.pojo.domain.SimpleUser;
import com.hghivln.pojo.dto.MenuDto;
import com.hghivln.pojo.vo.AjaxResult;
import com.hghivln.service.MenuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MenuServiceImpl implements MenuService{

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> selectMenuTree(Boolean isAdmin, SimpleUser simpleUser) {
        QueryWrapper<Menu> qw = new QueryWrapper<>();
        qw.eq(Menu.COL_STATUS, Constants.STATUS_TRUE);
        qw.eq(Menu.COL_DEL_FLAG,Constants.DEL_FALSE);
        qw.in(Menu.COL_MENU_TYPE,Constants.MENU_TYPE_M,Constants.MENU_TYPE_C);
        qw.orderByAsc(Menu.COL_PARENT_ID);
        if (isAdmin) {
            return menuMapper.selectList(qw);
        } else {
            // 普通用户：根据用户id 查询用户拥有的菜单信息
            return menuMapper.selectList(qw);
            //return menuMapper.selectMenuListByUserId(simpleUser.getUserId());
        }
    }

    @Override
    public AjaxResult listAllMenus(MenuDto menuDto) {
        QueryWrapper<Menu> qw = new QueryWrapper<>();
        qw.like(StringUtils.isNotBlank(menuDto.getMenuName()),Menu.COL_MENU_NAME,menuDto.getMenuName());
        qw.eq(Menu.COL_STATUS,Constants.STATUS_TRUE);
        return AjaxResult.success(menuMapper.selectList(qw));
    }

    @Override
    public AjaxResult addMenu(MenuDto menuDto) {
        Menu menu = new Menu();
        BeanUtil.copyProperties(menuDto,menu);
        menu.setCreateBy(menuDto.getSimpleUser().getUserName());
        menu.setCreateTime(DateUtil.date());
        return AjaxResult.success(menuMapper.insert(menu));
    }

    @Override
    public AjaxResult updateMenu(MenuDto menuDto) {
        Menu menu = new Menu();
        BeanUtil.copyProperties(menuDto,menu);
        menu.setUpdateBy(menuDto.getSimpleUser().getUserName());
        return AjaxResult.success(menuMapper.updateById(menu));
    }

    @Override
    public AjaxResult deleteMenuById(Long id) {
        return AjaxResult.success(menuMapper.deleteMenuById(id));
    }

    @Override
    public boolean hasChildByMenuId(Long menuId) {
        Long count = menuMapper.queryChildCountByMenuId(menuId);
        return count > 0L;
    }

    @Override
    public AjaxResult getMenuById(Long id) {
        return AjaxResult.success(menuMapper.selectById(id));
    }

    @Override
    public AjaxResult getMenuIdsByRoleId(Long roleId) {
        return AjaxResult.success(menuMapper.queryMenuIdsByRoleId(roleId));
    }
}
